/*
 * @Author: Marte
 * @Date:   2016-10-28 09:46:58
 * @Last Modified by:   Marte
 * @Last Modified time: 2016-10-28 15:36:38
 */

'use strict';

/**
 * 使用前须知:
 *
 * 调用文件的html应加载的css:
 *
 * link(href="/css/imagewall.css", rel="stylesheet")
 *
 * 调用文件的html应加载的js:
 *
 * script(src="/js/qf.imageSelect.js") (本文件)
 *
 * 调用文件的前端js应依赖的模板
 *
 * [qf.imageSelect']
 *
 * 调用文件的前端controller应依赖的服务
 *
 * 'imageSelectService'
 *
 */
angular.module('qf.imageSelect', ['ui.bootstrap']);

var globalOp;

angular.module('qf.imageSelect')
    /*  .factory('imageClassDataCache', ['$cacheFactory', function($cacheFactory) {
        return $cacheFactory('image-class-data-cache');
      }])*/
    .service('imageSelectService', ['$modal',
        'selectImageTemplate',
        function($modal, selectTemplate) {

            // 调试页面效果时才用,正式应将模板包含在js文件中
            // this.selectTemplate = '/static/admin/htmlTemplate/qf.imageSelectByClass.temp.html';

            /**
             * [selectImage 选择图片]
             * @param  {obj} op             [选项]
             * @param  {function} okCallback     [选择后回调]
             * @param  {function} cancelCallback [取消后回调]
             * @return {void}                [无]
             *
             * op的格式:
             * {
             *  onSelectEvent: function,
             *    //选择图片时的回调函数
             *    //回调函数参数:
             *    //function(start , size){}
             *    //回调函数需要返回 Promise
             *    //Promise需要查询图片结果对象(包括记录总数)
             *    //图片结果对象的格式:
             *    //{count:number,rows:[]}
             *    //
             *  onPageChangeEvent: function,
             *    //点击分页页码时的回调函数
             *    //回调函数参数:
             *    //function(start , size){}
             *    //回调函数需要返回 Promise
             *    //Promise需要查询图片结果对象
             *    //图片结果对象的格式:
             *    //{rows:[]}
             *
             *  resourceFields:{
             *    //资源的相关字段名
             *    resourceFileName:'', //资源文件名
             *    resourceTitle:'', //资源标题
             *
             *  }
             * }
             *
             *
             */
            this.selectImage = function(op, okCallback, cancelCallback) {
                var self = this;
                globalOp = op;
                var modalInstance = $modal.open({
                    animation: true,
                    template: selectTemplate,
                    controller: 'selectImageCtrl',
                    controllerAs: 'vm',
                    bindToController: true,
                    size: op.size || 'lg',
                    resolve: {
                        op: op,
                    }
                });
                modalInstance.result.then(function(selectItem) {
                    if (okCallback) {
                        okCallback(selectItem);
                    }
                }, function() {
                    if (cancelCallback) {
                        cancelCallback();
                    }
                });
            };
        }
    ])
    .controller('selectImageCtrl', ['$scope', '$modalInstance', 'op',
        function($scope, $modalInstance, op) {
            var vm = this;

            vm.op = globalOp;
            /*      vm.treedata = op.classData || [];
                  vm.currClass = vm.treedata[0];*/
            vm.currResources = [];
            // 资源分页用
            vm.listAllRecordCount = 0;
            vm.currPage = 1;
            vm.pageCount = 0;
            vm.pageSize = 8;

            vm.selectItem = null;

            //
            $scope.ok = function() {
                $modalInstance.close(vm.selectItem);
            };

            $scope.cancel = function() {
                $modalInstance.dismiss();
            };
            vm.selectResource = function(resource) {
                vm.selectItem = resource;
                $scope.ok();
            };
            /*      vm.selectNode = function(selectClass, $event) {
                    //要执行onSelectClassEvent
                    $event.stopPropagation();
                    vm.currClass = selectClass;
                    vm.currPage = 1;
                    vm.getPagedata(vm.currClass, true);
                  };*/
            vm.getPageStart = function(page) {
                return (page - 1) * vm.pageSize;
            };

            vm.getPagedata = function(isCountAll) {
                var dataPromise = null;

                if (isCountAll) {
                    if (vm.op.onSelectEvent) {
                        dataPromise = vm.op.onSelectEvent(
                            vm.getPageStart(vm.currPage), vm.pageSize);
                    }
                } else {
                    if (vm.op.onSelectEvent) {
                        dataPromise = vm.op.onPageChangeEvent(vm.getPageStart(vm.currPage), vm.pageSize);
                    }
                }
                if (dataPromise) {
                    dataPromise.then(function(data) {
                      console.log(vm.getPageStart(vm.currPage));
                      console.log(vm.pageSize);
                        if (isCountAll) {
                            vm.setListAllRecordCount(data.count);
                        }
                        vm.setListdata(data.rows);
                    });
                }
            };
            vm.setListAllRecordCount = function(allCount) {
                vm.pageCount = Math.ceil(allCount / vm.pageSize);
                vm.listAllRecordCount = allCount;
                console.log(vm.pageCount);
                console.log(vm.listAllRecordCount);
            };
            vm.setListdata = function(listdata) {
                vm.currResources = listdata;
                //console.log(vm.currResources);
            };
            vm.pageChanged = function() {
                console.log('change');
                vm.getPagedata(false);
            };
            vm.getPagedata(true);

        }
    ]);

angular.module('qf.imageSelect')
    .constant('selectImageTemplate', ['<style>',
        '  .modal-body{',
        '   min-height: 600px;',
        '   padding:5px;',
        '  }',
        '  .modal-footer{',
        '   padding:5px;',
        '  }',
        '  .modal-content #classbox{',
        '   min-height: 600px;',
        '   max-height: 780px;',
        '   overflow:auto;',
        '  }',
        '  .modal-content #imagewallbox{',
        '   min-height: 600px;',
        '   max-height: 780px;',
        '   overflow-y:auto;',
        '   overflow-x:hidden;',
        '  }',
        '  .pagination{',
        '   margin-top:10px;',
        '   margin-left:20px;',
        '   vertical-align: middle;',
        '  }',
        '  .imagewallbox-header span{',
        '   display: inline-block;',
        '   vertical-align: middle;',
        '   margin: 0 10px 0 10px;',
        '  }',
        '</style>',
        '<div>',
        '  <div class="modal-header">',
        '    <button type="button" ng-click="cancel()" class="close"></button>',
        '  </div>',
        '  <div class="modal-body">',
        '            <div id="imagewallbox">',
        '              <div class="box-body">',
        '                <div class="imagewallbox-header"><span class="h4">图片列表</span>',
        '                </div>',
        '                <div class="row imagewall">',
        '                  <div ng-repeat="resource in vm.currResources" class="col-md-3">',
        '                    <div class="box box-solid">',
        '                      <div class="box-body imagewall-box-body">',
        '                        <div class="img-container"><img ng-src="/resource/{{resource[vm.op.resourceFields.resourceFileName]}}" class="img-responsive center-block"/></div>',
        '                      </div>',
        '                      <div class="box-footer">',
        '                        <div>',
        '                          <div>',
        '                            <p class="line2text">{{resource[vm.op.resourceFields.resourceTitle]}}</p>',
        '                          </div>',
        '                        </div>',
        '                        <div>',
        '                          <div>',
        '                            <button type="button" ng-click="vm.selectResource(resource)" class="btn btn-success btn-xs">选择</button>',
        '                          </div>',
        '                        </div>',
        '              </div>',
        '            </div>',
        '          </div>',
        '              <div class="pagination col-md-12 clearfix">',
        '                <pagination class="pull-left" ng-change="vm.pageChanged()" boundary-links="true" total-items="vm.listAllRecordCount" ng-model="vm.currPage" items-per-page="vm.pageSize" max-size="5" previous-text="&lsaquo;" next-text="&rsaquo;" first-text="&laquo;" last-text="&raquo;" ng-show="vm.listAllRecordCount > 0">                             </pagination>',
        '              </div>',
        '        </div>',
        '      </div>',
        '    </div>',
        '  </div>',
        '  <!-- <div class="modal-footer">',
        '    <button type="button" ng-click="cancel()" class="btn btn-primary">取消</button>',
        '  </div> -->',
        '</div>'
    ].join(''));
